﻿// -----------------------------------------------------------------------
// <copyright file="ConfigController.cs" company="Microsoft">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

namespace ConfigManager
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Diagnostics;
    /// <summary>
    /// TODO: Update summary.
    /// </summary>
   

    public sealed class ConfigController
    {
        private static volatile ConfigController instance;
        private static object syncRoot = new Object();
        private List<IConfigNotify> notifyReceivers = new List<IConfigNotify>();

        private ConfigController() { }

        public static ConfigController Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (syncRoot)
                    {
                        if (instance == null)
                        {
                            instance = new ConfigController();
                        }
                    }
                }

                return instance;
            }
        }



        public bool RegisterNotifyReceiver(IConfigNotify notifyReceiver)
        {
            if (null == notifyReceiver)
            {
                return false;
            }
            Debug.WriteLine("ConfigController.RegisterNotifyReceiver--New Notify receiver is coming!");

            notifyReceivers.Add(notifyReceiver);
            return true;
        }

        public bool SaveConfigration(string cfgContent, ConfigType cfgType)
        {
            Debug.WriteLine("ConfigController.SaveConfigration--Save new configration: %s", cfgContent);
            SendChangeNotification(cfgType, "TestFile");
            return true;
        }

        private void SendChangeNotification(ConfigType configType, string configFile)
        {
            Debug.WriteLine("ConfigController.SendChangeNotification--Start to send configration changed notification!");
            foreach( IConfigNotify notifyReceiver in notifyReceivers)
            {
                notifyReceiver.ConfigChange(configType, configFile);
            }
            Debug.WriteLine("ConfigController.SendChangeNotification--Finished to send configration changed notification!");

        }


    }
}
